package com.sinothk.gpserver.modules.biz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sinothk.gpserver.data.DataConstant;
import com.sinothk.gpserver.modules.biz.entity.GroupCoinsLogEntity;
import com.sinothk.gpserver.modules.biz.entity.GroupCoinsVo;
import com.sinothk.gpserver.modules.biz.entity.GroupMemberEntity;
import com.sinothk.gpserver.modules.biz.mapper.GroupCoinsLogMapper;
import com.sinothk.gpserver.modules.biz.mapper.GroupMemberMapper;
import com.sinothk.gpserver.modules.biz.service.IGroupCoinsLogService;
import com.sinothk.gpserver.modules.system.entity.LoginEntity;
import com.sinothk.gpserver.modules.system.entity.UserEntity;
import com.sinothk.gpserver.modules.system.mapper.UserMapper;
import com.sinothk.gpserver.util.PageDataUtil;
import com.sinothk.server.support.annotation.callback.BizException;
import com.sinothk.server.support.entity.PageData;
import com.sinothk.server.support.entity.PageVo;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * <p>
 * 金币发放功能 服务实现类
 * </p>
 *
 * @author Liang Y.t.
 * @since 2021-09-14
 */
@Service
public class GroupCoinsLogServiceImpl extends ServiceImpl<GroupCoinsLogMapper, GroupCoinsLogEntity> implements IGroupCoinsLogService {

    @Resource
    private GroupCoinsLogMapper groupCoinsLogMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private GroupMemberMapper groupMemberMapper;

    /**
     * 查询分页数据
     *
     * @param pageVo 分页参数
     * @return PageData
     */
    @Override
    public PageData<GroupCoinsLogEntity> page(PageVo<GroupCoinsLogEntity> pageVo) {
        Page<GroupCoinsLogEntity> page = new Page<>(pageVo.getPageNum(), pageVo.getPageSize());

        LambdaQueryWrapper<GroupCoinsLogEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(GroupCoinsLogEntity::getSetAccount, pageVo.getData().getSetAccount());
        wrapper.eq(GroupCoinsLogEntity::getGroupId, pageVo.getData().getGroupId());

        wrapper.orderByDesc(GroupCoinsLogEntity::getCreateTime);

        IPage<GroupCoinsLogEntity> iPage = groupCoinsLogMapper.selectPage(page, wrapper);
        return new PageDataUtil<GroupCoinsLogEntity>().create(iPage);
    }

    @Override
    @Transactional(rollbackFor = BizException.class)
    public void addLog(GroupCoinsVo vo) {
        int valueInt = 0;
        try {
            valueInt = Integer.parseInt(vo.getGetCoins());
        } catch (Exception e) {
            throw new BizException("输入积分数有误");
        }
        LoginEntity login = (LoginEntity) SecurityUtils.getSubject().getPrincipal();
        LambdaQueryWrapper<GroupMemberEntity> groupMemberWrapper = new LambdaQueryWrapper<>();
        groupMemberWrapper.eq(GroupMemberEntity::getGroupId, vo.getGroupId())
                .eq(GroupMemberEntity::getMemberAccount, login.getAccount());
        GroupMemberEntity groupMemberLoader = groupMemberMapper.selectOne(groupMemberWrapper);

        if (groupMemberLoader == null) throw new BizException("异常，你不是群内成员");
        if (groupMemberLoader.getGroupRole() == null
                || !(groupMemberLoader.getGroupRole() == DataConstant.RoleGroup.G_ADMIN || groupMemberLoader.getGroupRole() == DataConstant.RoleGroup.G_PARTNER)
        ) throw new BizException("权限不够，只有群管理员或合伙人有操作权限");

        // 增减上分人 积分
        if (groupMemberLoader.getGroupRole() == DataConstant.RoleGroup.G_PARTNER) {
            float coinsForLoader = groupMemberLoader.getMemberCoins() == null ? 0 : groupMemberLoader.getMemberCoins();
            if (vo.getType() == 0) {//类型：0 发出；1 收回
                if (coinsForLoader < valueInt) throw new BizException("你给当前积分已小于上分数量，上分失败");
                groupMemberLoader.setMemberCoins(coinsForLoader - valueInt);
            } else {
                groupMemberLoader.setMemberCoins(coinsForLoader + valueInt);
            }
            groupMemberMapper.updateById(groupMemberLoader);
        }

        // 设置被上分人信息 给被上分人加减分
        LambdaQueryWrapper<GroupMemberEntity> groupMemberWrapperGET = new LambdaQueryWrapper<>();
        groupMemberWrapperGET.eq(GroupMemberEntity::getGroupId, vo.getGroupId())
                .eq(GroupMemberEntity::getMemberAccount, vo.getGetAccount());

        GroupMemberEntity groupMemberGET = groupMemberMapper.selectOne(groupMemberWrapperGET);
        if (groupMemberGET == null) throw new BizException("异常，上分对象不是群内成员");

        float oldCoins = groupMemberGET.getMemberCoins() == null ? 0 : groupMemberGET.getMemberCoins();
        if (vo.getType() == 0) {//类型：0 发出；1 收回
            groupMemberGET.setMemberCoins(oldCoins + valueInt);
        } else {
            if (oldCoins < valueInt) throw new BizException("收回积分不能大于对方现有积分");
            groupMemberGET.setMemberCoins(oldCoins - valueInt);
        }
        groupMemberMapper.updateById(groupMemberGET);

        // 设置群内积分实体
        GroupCoinsLogEntity roomCardLog = new GroupCoinsLogEntity();
        roomCardLog.setSetAccount(login.getAccount());
        roomCardLog.setCreateBy(login.getAccount());

        // 得到人信息
        UserEntity getUser = userMapper.selectByAccount(vo.getGetAccount());
        if (getUser == null) throw new BizException("发放对象不存在");
        roomCardLog.setGetAccount(vo.getGetAccount());
        roomCardLog.setGetAvatar(getUser.getUserAvatar());
        roomCardLog.setGetName(getUser.getUserName());
        //
        roomCardLog.setGroupId(vo.getGroupId());
        roomCardLog.setType(vo.getType());
        roomCardLog.setSetInfo(login.getAccount() + "发给" + vo.getGetAccount());
        roomCardLog.setGetCoins(valueInt);
        this.save(roomCardLog);
    }
}
